package main
// 引入相关包
import (
	"database/sql"
	_"dm"
	"fmt"
	"os"
	"strings"
	"bufio"
)

var db *sql.DB
var err error

func main() {
	var name string
	var passwd string
	var ip string
	var port string
	
	if len(os.Args) ==1{
	name="SYSDBA"
	passwd="SYSDBA"
	ip="127.0.0.1"
	port="5236"
	}
	
	if len(os.Args) ==4 {
		if strings.Index(os.Args[3],":")==-1{
			name=os.Args[1]
			passwd=os.Args[2]
			ip=os.Args[3]
			port="5236"
		}else{
			name=os.Args[1]
			passwd=os.Args[2]
			ip="127.0.0.1"
			port=os.Args[3][1:]
		}
	}
	
	if len(os.Args) ==5{
		name=os.Args[1]
		passwd=os.Args[2]
		ip=os.Args[3]
		port=os.Args[4]
	}
	
	
	driverName := "dm"
	dataSourceName := "dm://"+name+":"+passwd+"@"+ip+":"+port+""

	if db, err = connect(driverName, dataSourceName); err != nil {
		fmt.Println(err)
		return
	}
	if err = CTab(); err != nil {
		fmt.Println(err)
		return
	}
	
	var (Input string
	a []string
	 )
	
	f := bufio.NewReader(os.Stdin) //读取输入的内容
	for {
		fmt.Print(">")
		Input,_ = f.ReadString('\n') //定义一行输入的内容分隔符。
		if len(Input) == 1 {
			continue //如果用户输入的是一个空行就让用户继续输入。
		}
		Input= strings.Replace(strings.Replace(Input, "\n", "", -1), "\r", "", -1)
		
		println(Input)
		
		Input=strings.ToLower(Input)
		
		a=strings.Split(Input, " ")
		if len(a)==2 {
			switch strings.ToLower(a[0]){
				case "tabs":
					tabs(strings.ToUpper(a[1]))
				case "gc":
					gc(strings.ToUpper(a[1]))
				case "gu":
					gu()
		}
			
		}
		

		
		
		//if err = CTab(); err != nil {
		//	fmt.Println(err)
		//	return
		//}

		//fmt.Sscan(Input,&String,&Number) //将Input
		if Input == "exit" || Input == "q" || Input == "quit" {
			println("--")
			break
		}
		
	}

	if err = disconnect(); err != nil {
		fmt.Println(err)
		return
	}
}

/* 新建表 */
func CTab() error {
        var sql = `create or replace
					procedure sysdba.gb1
					as
					begin
							select
									datediff(ss, last_recv_time, sysdate) diff,
									(
											select
													b.blocked
											from
													v$lock b
											where
													b.trx_id=a.trx_id
											order by
													blocked desc limit 1
									)
									blocked ,
									a.trx_id,
									a.*
							from
									v$sessions a
							where
									a.trx_id in
									(
											/*select  row_idx from  v$Lock where blocked=1 union all
											select  trx_id from  v$Lock where blocked=1*/
											SELECT
													id
											FROM
													V$TRXWAIT
											
											union all
											
											select wait_for_id from v$trxwait
									) ;
					end;
					`
		//fmt.println(sql)
        if _, err := db.Exec(sql); err != nil {
                return err
        }
        fmt.Println("updateTable succeed")
        return nil
}


/* 创建数据库连接 */
func connect(driverName string, dataSourceName string) (*sql.DB, error) {
	var db *sql.DB
	var err error
	if db, err = sql.Open(driverName, dataSourceName); err != nil {
		return nil, err
	}
	if err = db.Ping(); err != nil {
		return nil, err
	}
	fmt.Printf("connect to \"%s\" succeed.\n", dataSourceName)
	return db, nil
}

/* 查询产品信息表 */
func tabs(owner string) error {
	var str1 string
	//var name string
	//var author string
	//var description dm.DmClob
	//var photo dm.DmBlob
	var sql = "SELECT table_name FROM dba_tables WHERE owner=:owner"
	rows, err := db.Query(sql,owner)
	if err != nil {
		return err
	}
	defer rows.Close()
	fmt.Println("queryTable results:")
	for rows.Next() {
		if err = rows.Scan(&str1); err != nil {
			return err
		}
		// blobLen, _ := photo.GetLength()
		fmt.Printf("%v\n", str1)
	}
	return nil
}

/* 查询产品信息表 */
func gu() error {
	var str1 string
	var str2 string
	//var author string
	//var description dm.DmClob
	//var photo dm.DmBlob
	var sql = "SELECT username,to_char(created,'yyyy-mm-dd hh24:mi') FROM all_users order by created"
	rows, err := db.Query(sql)
	if err != nil {
		return err
	}
	defer rows.Close()
	fmt.Println("queryTable results:")
	for rows.Next() {
		if err = rows.Scan(&str1,&str2); err != nil {
			return err
		}
		// blobLen, _ := photo.GetLength()
		fmt.Printf("%v\t %v\n", str1,str2)
	}
	return nil
}
func gc(ot string) error {
	var str1 int
	//var name string
	//var author string
	//var description dm.DmClob
	//var photo dm.DmBlob
	var sql = "SELECT count(*) FROM "+ot
	rows, err := db.Query(sql)
	if err != nil {
		return err
	}
	defer rows.Close()
	fmt.Println("queryTable results:")
	for rows.Next() {
		if err = rows.Scan(&str1); err != nil {
			return err
		}
		// blobLen, _ := photo.GetLength()
		fmt.Printf("%v\n", str1)
	}
	return nil
}


/* 关闭数据库连接 */
func disconnect() error {
	if err := db.Close(); err != nil {
		fmt.Printf("db close failed: %s.\n", err)
		return err
	}
	fmt.Println("disconnect succeed")
	return nil
}

